package com.homedo.odin.solution.service;

import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.service.BaseService;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.odin.solution.dao.HundredStylistInfoMapper;
import com.homedo.odin.solution.dao.HundredStylistSolutionApplyInfoMapper;
import com.homedo.odin.solution.dao.SolutionMapper;
import com.homedo.odin.solution.enumcode.PublicDeleteEnum;
import com.homedo.odin.solution.model.entity.HundredStylistInfo;
import com.homedo.odin.solution.model.entity.HundredStylistSolutionApplyInfo;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.request.activity.SolutionApplyInfoRequestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * @author: zhanglei
 * @date: 2018/4/25
 * @Description:
 */
@Service
public class HundredStylistSolutionApplyInfoServiceImpl extends
        BaseService<HundredStylistSolutionApplyInfoMapper, HundredStylistSolutionApplyInfo> {

    @Autowired
    private HundredStylistInfoMapper hundredStylistInfoDao;

    @Autowired
    private SolutionMapper solutionDao;

    /**
     * PC百名设计师评选  提交参评方案
     */
    public void saveSolutionApplyInfo(SolutionApplyInfoRequestBean requestBean) {
        HundredStylistInfo hundredStylistInfo = hundredStylistInfoDao.selectByUserId(requestBean.getUserId());
        if (hundredStylistInfo == null) {
            throw new BizException(Meta.CODE_451.getCode(), "百名设计师活动，该设计师未录入评选信息，不能提交参评方案");
        }

        //校验提交评审的方案是否存在
        Long solutionId = requestBean.getSolutionId();
        Solution solution = solutionDao.findBySolutionIdAndDelAndStatus(solutionId, requestBean.getUserId(),
                PublicDeleteEnum.NOT_DEL.getDbValue());
        if (solution == null) {
            throw new BizException(Meta.CODE_451.getCode(), "百名设计师活动，该方案不存在");
        }

        HundredStylistSolutionApplyInfo transfrom = BeanUtils
                .transfrom(HundredStylistSolutionApplyInfo.class, requestBean);
        try {
            transfrom.setSolutionMatchPic(solution.getMatchPic());
            baseMapper.insert(transfrom);
        } catch (Exception ex) {
            //唯一索引 用户只能提交一次
            if (ex instanceof DuplicateKeyException) {
                throw new BizException(Meta.CODE_451.getCode(), "百名设计师活动，用户已提交过参评方案");
            }
            throw ex;
        }

    }
}
